//
//  HomePage.m
//  Demo_simple
//
//  Created by  on 15/7/8.
//  Copyright (c) 2015年 rain. All rights reserved.
//

#import "HomePage.h"
#import "AFNetworking.h"
#import "ViewController.h"
#import "SendViewController.h"
#import "XMLReader.h"
#import "WXNextWorking.h"
#import "GoodsAndNumCell.h"
@interface HomePage ()<CXCNavgationDelegate,UITableViewDelegate,UITableViewDataSource,WXNextWorkingDelegate>
{
    NSMutableArray *peopleArr;//存在本地的进度和人
    NSMutableArray*messageArr;//所有的消息

    UIImageView*mainImgView;
    UIImageView *touImgV;
    NSTimer  *timer;
    
    int  indexNum;//多线程
    dispatch_queue_t queue;//多线程
    UILabel *jinduLabel;
    NSString *seqString;//不等于0的时候重新加载
    NSString *isreturn;
    
    UITableView *tableview;
    //底部scrollview
    TPKeyboardAvoidingScrollView *bgScrollView;
    UIView *bottomView ;
    UIButton *addAddressBtn;
}
@end
static NSInteger number = 0;
@implementation HomePage
-(void)btnClickPush:(NSString *)str
{
}
- (void) asyncConcurrent
{
    NSLog(@"asyncConcurrent---begin");
    queue = dispatch_queue_create("test.queue", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"asyncConcurrent---end");
}
- (void)asynIntName
{
    dispatch_async(queue, ^{
        WXNextWorking *wxNext =[[WXNextWorking alloc]init];
        wxNext.delegate =self;
        wxNext.pushArr =_pushArr;
        wxNext. messageArr =messageArr;
        wxNext.indexInPeopleArr =indexNum;
        [wxNext getErweima];
    });
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden =YES;
    [ProgressHUD dismiss];
    
}
//首页
- (void)viewDidLoad {
    [super viewDidLoad];
    //底部scrollview
    bgScrollView =[[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0,CXCWidth, CXCHeight )];
    [bgScrollView setUserInteractionEnabled:YES];
    [bgScrollView setBackgroundColor:BGColor];
    [self.view addSubview:bgScrollView];
    bgScrollView.showsVerticalScrollIndicator =NO;
    [bgScrollView setContentSize:CGSizeMake(CXCWidth, 1330*Width)];

    timer =  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(reloadDataTable) userInfo:nil repeats:YES];

    peopleArr =[[NSMutableArray alloc]init];
    indexNum =0;
     [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
       [self asyncConcurrent];
    messageArr =[[NSMutableArray alloc]init];
    
    for (int i=0; i<_pushArr.count; i++) {
        NSDictionary *dic =_pushArr[i];
        NSMutableArray *arr =[[NSMutableArray alloc]init];
        
        if (!([[dic objectForKey:@"img"]isEqual:[NSNull null]]))
        {
            if (!([[dic objectForKey:@"img"]isEqualToString:@""]||[[dic objectForKey:@"img"]isEqualToString:@"(null)"]||[[dic objectForKey:@"img"]isEqual:[NSNull null]])) {
                if([[dic objectForKey:@"type"]isEqualToString:@"2"])
                {
                    [arr addObject:@{@"img":[dic objectForKey:@"img"]}];

                }
            }
        }
        if (!([[dic objectForKey:@"content"]isEqual:[NSNull null]]))
        {
            if(!([[dic objectForKey:@"content"]isEqualToString:@""]||[[dic objectForKey:@"content"]isEqualToString:@"(null)"]))
            {
                [arr addObject:@{@"content":[dic objectForKey:@"content"]}];

            }
        }

        [messageArr addObject:arr];

    }
    NSLog(@"++++++++++++++++%@",messageArr);

    
    [self.view setBackgroundColor:BGColor];
    NavgationView *nav =[[NavgationView alloc]initWithFrame:CGRectMake(0, 0, CXCWidth, 64) with:@"分享系统" isBackBtn:@"YES" rightBtnName:@"NO"];
    nav.delegate =self;
    [self.view addSubview:nav];
    nav.navLabel.text =@"爆客系统";
    self.view.backgroundColor =BGColor;
    mainImgView =[[UIImageView   alloc]initWithFrame:CGRectMake(60*Width, 200*Width, 630*Width,630*Width)];
    [mainImgView setUserInteractionEnabled:YES];
    [mainImgView setBackgroundColor:[UIColor whiteColor]];
//    [mainImgView.layer setBorderWidth:5.0*Width];
    [mainImgView.layer setMasksToBounds:YES];
    mainImgView.layer.borderColor =NavColor.CGColor;
    [bgScrollView addSubview:mainImgView];
    
    touImgV =[[UIImageView alloc]initWithFrame:CGRectMake(225*Width, 225*Width, 180*Width,180*Width)];
    [touImgV setUserInteractionEnabled:YES];
    [touImgV setBackgroundColor:[UIColor yellowColor]];
    [touImgV.layer setBorderWidth:5.0*Width];
    [touImgV.layer setMasksToBounds:YES];
    touImgV.hidden =YES;
    touImgV.layer.borderColor =[UIColor whiteColor].CGColor;
    [mainImgView addSubview:touImgV];
//    jinduLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, mainImgView.bottom+20*Width, CXCWidth, 50*Width)];
//    jinduLabel.text =@"";
//    jinduLabel.textColor =TextGrayColor;
//    jinduLabel.textAlignment =NSTextAlignmentCenter;
//    jinduLabel.font =[UIFont systemFontOfSize:12];
//    [bgScrollView addSubview:jinduLabel];

    addAddressBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addAddressBtn setFrame:CGRectMake(190*Width,mainImgView.bottom+ 100*Width , 370*Width, 88*Width)];
    [addAddressBtn setBackgroundColor:NavColor];
    [addAddressBtn.layer setCornerRadius:4];
    [addAddressBtn.layer setMasksToBounds:YES];
    [addAddressBtn setTitle:@"刷新二维码" forState:UIControlStateNormal];
    [addAddressBtn.titleLabel setTextColor:[UIColor whiteColor]];
    [addAddressBtn.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [addAddressBtn addTarget:self action:@selector(reloadDataERweima) forControlEvents:UIControlEventTouchUpInside];
    [bgScrollView addSubview:addAddressBtn];
    WXNextWorking *wxNext =[[WXNextWorking alloc]init];
    wxNext.delegate =self;
    wxNext.pushArr =_pushArr;
    wxNext. messageArr =messageArr;
    wxNext.indexInPeopleArr =indexNum;
    [wxNext getErweima];
    if (![PublicMethod getObjectForKey:shopingCart]) {
        NSMutableArray *arr =[[NSMutableArray alloc]init];
        [PublicMethod setObject:arr key:shopingCart];
    }
    
    bottomView =[[UIView alloc]initWithFrame:CGRectMake(0, addAddressBtn.bottom+150*Width, CXCWidth, 150*Width)];
//    bottomView.backgroundColor =[UIColor redColor];
    [bgScrollView addSubview:bottomView];
    
    tableview  =[[UITableView alloc]init];
    [bgScrollView addSubview:tableview];
    [tableview setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [tableview setFrame:CGRectMake(0,addAddressBtn.bottom+80*Width, CXCWidth, 0*Width)];
    [tableview setDelegate:self];
    [tableview setDataSource:self];
    [tableview setBackgroundColor:[UIColor clearColor]];
    tableview .showsVerticalScrollIndicator = NO;

    
    UILabel *centerLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0*Width, CXCWidth, 50*Width)];
    centerLabel.text =@"免责声明：商家内容与分享系统无关";
    centerLabel.textColor =TextGrayGrayColor;
    centerLabel.textAlignment =NSTextAlignmentCenter;
    centerLabel.font =[UIFont systemFontOfSize:12];
    [bottomView addSubview:centerLabel];
    
    UILabel *bottomLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, centerLabel.bottom+30*Width, CXCWidth, 50*Width)];
    bottomLabel.text =@"技术支持：山东桥通天下网络科技有限公司";
    bottomLabel.textColor =TextGrayColor;
    bottomLabel.textAlignment =NSTextAlignmentCenter;
    bottomLabel.font =[UIFont systemFontOfSize:12];
    [bottomView addSubview:bottomLabel];
    
}
- (void)retunButtonAction
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.operationQueue cancelAllOperations];
    isreturn =@"YES";
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)reloadDataERweima
{
    touImgV.hidden =YES;
    [self asynIntName];
    indexNum++;
}
+(NSData *)returnDataWithDictionary:(NSDictionary*)dict
{
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:dict forKey:@"talkData"];
    [archiver finishEncoding];
    return data;
}

+ (NSString*)getMD5WithData:(NSData *)data{
    const char* original_str = (const char *)[data bytes];
    unsigned char digist[CC_MD5_DIGEST_LENGTH]; //CC_MD5_DIGEST_LENGTH = 16
    CC_MD5(original_str, (uint)strlen(original_str), digist);
    NSMutableString* outPutStr = [NSMutableString stringWithCapacity:10];
    for(int  i =0; i<CC_MD5_DIGEST_LENGTH;i++){
        [outPutStr appendFormat:@"%02x",digist[i]];//小写x表示输出的是小写MD5，大写X表示输出的是大写MD5
    }
    return [outPutStr lowercaseString];
    
}
-(void)returnTheERWEIMA:(NSString *)erweima
{
    mainImgView.hidden =NO;
    mainImgView.image =[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://login.weixin.qq.com/qrcode/%@",erweima]]]];
}
-(void)returnHeader:(UIImage *)erweima
{
    
//    [peopleArr addObject:erweima];
    touImgV.image =erweima;
    touImgV.hidden =NO;
    
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSLog(@"%@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return peopleArr.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return  80*Width;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellWithNumber";
    
    GoodsAndNumCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[GoodsAndNumCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier ];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        
    }
    NSDictionary *dict = peopleArr[indexPath.row];
    [cell setDic:dict];
    
    return cell;
}
- (void)reloadDataTable
{
    peopleArr =[PublicMethod getObjectForKey:shopingCart];
    if (peopleArr.count<8) {
        [tableview setFrame:CGRectMake(0, addAddressBtn.bottom+150*Width, CXCWidth, peopleArr.count*80*Width)];
    }else
    {
        [tableview setFrame:CGRectMake(0, addAddressBtn.bottom+150*Width, CXCWidth,8*80*Width)];
    }
    
    bottomView.frame =CGRectMake(0, tableview.bottom, CXCWidth, 150*Width);
    [bgScrollView setContentSize:CGSizeMake(CXCWidth, bottomView.bottom)];

    [tableview  reloadData];


}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}


@end
